package users

import (
	"github.com/gin-gonic/gin"
	"go_auth/ext/app"
	"go_auth/ext/e"
	"go_auth/ext/settings"
	"go_auth/servers/users"
	"go_auth/utils/commons"
	"net/http"
)

func Source(c *gin.Context) {
	sourceName := c.PostForm("sourceName")
	sourceOp := c.PostForm("sourceOp")
	shareToken := c.PostForm("shareToken")
	opt := c.PostForm("type")
	var appG = app.Gin{C: c}

	code := e.Success

	i, b := commons.StrToInt(shareToken)
	if !b {
		appG.Response(http.StatusOK, e.AtoB, sourceName)
		return
	}
	source := users.Source{}
	if i == 1 {
		source.SourceId = commons.EncodeMd5(sourceName)
	} else {
		source.SourceId = commons.EncodeMd5(commons.StringJoin([]string{sourceName, sourceOp}))
	}
	source.SourceName = sourceName
	source.SourceOp = sourceOp
	source.ShareToken = i

	if opt == settings.Add {
		flag := source.AddSource()
		if flag != e.Success {
			code = e.AddError
		} else {
			code = flag
		}
		appG.Response(http.StatusOK, code, sourceName)
		return
	}
	id := c.PostForm("id")
	ids, idb := commons.StrToInt(id)
	if !idb {
		appG.Response(http.StatusOK, e.AtoB, sourceName)
		return
	}
	source.Id = int64(ids)
	if opt == settings.Update {
		if source.UpdateSource() == e.Success {
			code = e.UpdateError
		}
	} else if opt == settings.Delete {
		if source.DeleteSource() == e.Success {
			code = e.DeleteError
		}
	} else {
		code = e.ParamsError
	}
	appG.Response(http.StatusOK, code, sourceName)
}

func FindSources(c *gin.Context) {
	source := users.Source{}
	sources := source.FindSources()
	var appG = app.Gin{C: c}
	code := e.Success

	if sources == nil {
		code = e.EmptyError
	}

	appG.Response(http.StatusOK, code, sources)
}
